﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Reflection;
using System.IO;
using System.Xml;
namespace Peer
{
    public class PeerUtils
    {
        public static DateTime? StringToDateTime(string str)
        {
            DateTime time;
            if (!string.IsNullOrEmpty(str)&&DateTime.TryParse(str, out time))
            {
                return new DateTime?(time);
            }
            else
            {
                return null;
            }
        }
        public static string RepeatString(string str, int n)
        {
            char[] arr = str.ToCharArray();
            char[] arrDest = new char[arr.Length * n];
            for (int i = 0; i < n; i++)
            {
                Buffer.BlockCopy(arr, 0, arrDest, i * arr.Length * 2, arr.Length * 2);
            }
            return new string(arrDest); 
        }
        public static void StreamCopy(Stream source, Stream destination)
        {
            byte[] buffer = new byte[512];
            bool copying = true;
            while (copying)
            {
                int bytesRead = source.Read(buffer, 0, buffer.Length);
                if (bytesRead > 0)
                {
                    destination.Write(buffer, 0, bytesRead);
                }
                else
                {
                    destination.Flush();
                    copying = false;
                }
            }
        }

        public static void ObjectCopy(object source, object destination)
        {
            foreach (PropertyInfo infos in source.GetType().GetProperties())
            {
                foreach (PropertyInfo infod in destination.GetType().GetProperties())
                {
                    if (infod.Name == infos.Name &&infod.PropertyType== infos.PropertyType)
                        infod.SetValue(destination, infos.GetValue(source,null), null);
                }
            }

        }

        public static void WebShowMessage(System.Web.UI.Page page,string message)
        {
            page.ClientScript.RegisterStartupScript(page.GetType(), "", string.Format("<script>alert(\"{0}\")</script>",message));
        }
        public static void WebShowMessage(System.Web.UI.Page page, string message, string gotoUri)
        {
            page.ClientScript.RegisterStartupScript(page.GetType(), "", string.Format("<script>alert(\"{0}\");location.href=\"{1}\";</script>", message,gotoUri));
        }
    }
}
